#include "recbox.h"
#include "recboxitem.h"
#include "ui_recbox.h"
#include <QJsonObject>
#include <myminimusic.h>
#include <QtMath>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);

}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    // 如果是两行
    if(2 == row)
    {
        this->row = row;
        this->col = 8;
    } else {
        // 否则只有一行，隐藏底下一行
        ui->recListDown->hide();
    }
    imageList = data;

    // 默认显示第0组
    currentIndex = 0;
    // 计算总组数 ceil向上取整
    count = ceil(imageList.size() / col);
    // 往RecItem中添加数据
    createRecItem();
}

void RecBox::createRecItem()
{
    // 当我们想往上或往后翻转时，需要先移除掉之前的元素
    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto e : recUpList)
    {
        ui->horizontalLayoutUp->removeWidget(e);
        delete e;
    }
    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto e : recDownList)
    {
        ui->horizontalLayoutDown->removeWidget(e);
        delete e;
    }
    // 创建RecBoxItem对象，添加到RecBox中
    int index = 0;
    for(int i = currentIndex*col; i < col + currentIndex*col; i++)
    {
        RecBoxItem* item = new RecBoxItem();

        QJsonObject obj = imageList[i].toObject();
        item->setText(obj.value("text").toString());
        item->setImage(obj.value("path").toString());

        // 将item添加到RecBox
        // 当col = 8 且 row == 2时 index:4, 5, 6, 7都应插入到horizontalLayoutDown中
        if(index >= col/2 && row == 2) {
            ui->horizontalLayoutDown->addWidget(item);
        } else {
            ui->horizontalLayoutUp->addWidget(item);
        }
        ++index;
    }
}

void RecBox::on_btUp_clicked()
{
    // 显示上一组数据，如果已经是第一组数据，就循环从后往前显示
    currentIndex--;
    if(currentIndex < 0) {
        currentIndex = count - 1;
    }
    createRecItem();
}

void RecBox::on_btDown_clicked()
{
    // 显示下一组数据，如果已经是最后一组数据，就循环从前往后显示
    currentIndex++;
    if(currentIndex == count) {
        currentIndex = 0;
    }
    createRecItem();
}
